﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Evoucher.Business.Security;
using Evoucher.Business.Models;
using Evoucher.Business;
using System.IO;
using Mani.Common;

public partial class Admin_import : System.Web.UI.Page
{
    public List<SoldVouchers> SoldVouchersByDay { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {
        GetSoldVouchersReport();

        if (!Page.IsPostBack)
        {
            LoadVoucherTypes();
            LoadVoucherStats();
        }
    }

    private void LoadVoucherTypes()
    {
        IVoucherRepository repo = new VoucherRepository();
        ddlVoucherTypes.DataTextField = "Description";
        ddlVoucherTypes.DataValueField = "Id";
        ddlVoucherTypes.DataSource = repo.GetVoucherTypes();
        ddlVoucherTypes.DataBind();
    }

    private void LoadVoucherStats()
    {
        IVoucherRepository voucherRepo = new VoucherRepository();
        lTotalVouchers.Text = voucherRepo.GetVouchersCount().ToString();
        lAvilableVouchers.Text = voucherRepo.GetReadyForSaleVouchers().ToString();
        lSoldVouchers.Text = voucherRepo.GetSoldVouchersCount().ToString();
    }

    protected void btnUploadFiles_Click(object sender, EventArgs e)
    {
        // ToDo Check File Extension and etc

        uploadSummary.Visible = false;
        txtSummary.Text = String.Empty;

        FileInfo fi = new FileInfo(fuUploader.PostedFile.FileName);
        if (fi.Extension.ToLower() != ".csv")
        {
            UIHelper.ClientAlert(this, "لطفا فایل ورودی را با فرمت سی اس وی وارد کنید");
            return;
        }

        StreamReader streamReader = new StreamReader(fuUploader.PostedFile.InputStream);
        IVoucherRepository voucherRepo = new VoucherRepository();
        List<Voucher> vouchers = new List<Voucher>();
        List<string> NotImportedSerials = new List<string>();

        string voucherTypeStr = ddlVoucherTypes.SelectedValue;
        VoucherType voucherType =  voucherRepo.GetVoucherTypeById(Convert.ToInt32(voucherTypeStr));
        string format = voucherType.Format;

        while (streamReader.Peek() != -1) {
            string nextLine = streamReader.ReadLine();
            nextLine = nextLine.Replace(" ", "");
            if (nextLine.Length < 2)
                continue;

            string[] voucherData = nextLine.Split(',');
                 
            string serial = String.Empty;
            string pin = String.Empty;

            if (voucherData.Length == 1)
            {
                string data = voucherData[0].Replace("IR", "");
                data = data.Replace(" ", "");
                int serialCount = Convert.ToInt32(format.Substring(format.IndexOf('S') + 1, format.IndexOf('P') - 1));
                int pinCount = Convert.ToInt32(format.Substring(format.IndexOf('P') + 1));

                serial = data.Substring(0, serialCount);
                pin = data.Substring(serialCount, pinCount);
            }
            else if (voucherData.Length >= 2)
            {
                serial = voucherData[0];
                pin = voucherData[1];
            }

            if (voucherRepo.GetVoucherBySerial(serial) != null)
            {
                NotImportedSerials.Add(serial);
                continue;
            }

            Voucher v = new Voucher();
            DateTime importDate = DateTime.Now;
            v.ImportDate = importDate;
            v.LastUpdateDate = importDate;
            v.Pin = TDESProvider.Encrypt(pin, importDate.ToString(), true);
            v.Serial = serial;
            v.VoucherType = voucherType;
            v.VoucherState = voucherRepo.GetVoucherStateById( (int)VoucherStates.ReadyForSale );
            vouchers.Add(v);
        }

        voucherRepo.ImportVoucher(vouchers);
        voucherRepo.persist();

        if (NotImportedSerials.Count == 0) {
            UIHelper.ClientAlert(this, "عملیات با موفقیت انجام شد");
        }
        else {
            UIHelper.ClientAlert(this, "تعدادی از شارژ کارت ها به دلیل تکراری بودن وارد سیستم نشدند که در پایین صفحه لیست شده اند");
            txtSummary.Text = String.Empty;

            foreach (string s in NotImportedSerials)
                txtSummary.Text += s + Environment.NewLine;

            uploadSummary.Visible = true;
        }

        LoadVoucherStats();
    }

    private void GetSoldVouchersReport()
    {
        IVoucherRepository repo = new VoucherRepository();
        List<SoldVouchers> result = repo.GetCountSoldVouchersByDay(DateTime.Now.AddDays(-5));

        if (result.Count == 0)
        {
            result.Add(new SoldVouchers { Date = DateTime.Now, Count = 0 });
            result.Add(new SoldVouchers { Date = DateTime.Now.AddDays(-1), Count = 0 });
            result.Add(new SoldVouchers { Date = DateTime.Now.AddDays(-2), Count = 0 });
            result.Add(new SoldVouchers { Date = DateTime.Now.AddDays(-3), Count = 0 });
            result.Add(new SoldVouchers { Date = DateTime.Now.AddDays(-4), Count = 0 });
        }
        else if (result.Count < 5)
        {
            int count = result.Count;
            for (int i = count; i < 5; i++)
            {
                result.Add(new SoldVouchers { Date = result[i - 1].Date.AddDays(-1), Count = 0 });
            }

        }

        SoldVouchersByDay = result;
    }

}